package me.fibonacci;

import java.util.Arrays;

public class FibonacciMemoization {
    // 记忆法(备忘录)改进，减少计算量 
    public static void main(String[] args) {
        int result = memoization(8);
        System.out.println(result);
    }

    public static int memoization(int n) {
        int[] cache = new int[n + 1];
        // 先用-1填充数组，表示还未计算
        Arrays.fill(cache, -1);
        // 索引0和1的结果已知，赋值
        cache[0] = 0;
        cache[1] = 1;
        return fibonacci(n, cache);
    }

    private static int fibonacci(int n, int[] cache) {
        if (cache[n] != -1) {
            return cache[n];
        }
        int x = fibonacci(n - 1, cache);
        int y = fibonacci(n - 2, cache);
        cache[n] = x + y;
        return cache[n];
    }
}
